package cn.aiseminar.aisinterphone;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

public class ConnectActivity extends Activity {
	private BluetoothPhoneService mPhoneService = null;
	
	private SoundPool mSP = null;	
	private int mSoundCalling = 0;
	
	@SuppressLint("HandlerLeak")
	private final Handler mMessageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what)
			{
			case BluetoothPhoneService.MSG_DEVICE_CONNECT_SUCCESS:
				startVoiceTalkingWithDevice();
				break;
			case BluetoothPhoneService.MSG_DEVICE_CONNECT_FAILED:
				String errorMsg = (String) msg.obj;
				Toast.makeText(ConnectActivity.this, errorMsg, Toast.LENGTH_LONG).show();
				ConnectActivity.this.finish();
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.calling_activity);
		
		mPhoneService  = BluetoothPhoneService.getBluetoothPhoneService();
        mPhoneService.setMsgHandler(mMessageHandler);
        
        initSP();
	}
		
	@Override
	protected void onStart() {
		super.onStart();
	}
		
	@Override
	protected void onStop() {
		mSP.stop(mSoundCalling);
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		if (null != mSP)
		{
			mSP.release();
			mSP = null;
		}
		super.onDestroy();
	}

	public void initSP()
	{
		mSP = new SoundPool(10, AudioManager.STREAM_SYSTEM, 0);
		mSoundCalling = mSP.load(this, R.raw.qav_video_request, 1);
		mSP.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
			
			@Override
			public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
				mSP.play(mSoundCalling, 1, 1, 0, -1, 1);			
			}
		});
	}
	
	public void startVoiceTalkingWithDevice()
	{
		Intent talkIntent = new Intent(ConnectActivity.this, VoiceActivity.class);
		startActivity(talkIntent);
		
		this.finish();
	}
}
